package com.dingreading.cloud.admin.util;

import com.dingreading.cloud.admin.entity.TimeTasks;
import com.dingreading.cloud.admin.service.TimeTasksService;
import com.dingreading.cloud.admin.util.redis.RedisService;
import com.dingreading.cloud.common.util.AccountUtil;
import com.dingreading.cloud.common.util.DateUtil;
import com.dingreading.cloud.common.util.HttpUtils;
import com.dingreading.cloud.common.util.RedisParam;
import com.dingreading.cloud.common.util.qyweixin.AccessTokenDto;
import com.dingreading.cloud.common.util.qyweixin.QyWeiXinUtil;
import com.dingreading.cloud.common.util.qyweixin.QyWeixinMsg;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RefreshScope
@Component
public class TimeTaskUtil {

    @Value("${envi}")
    private String envi;
    @Value("${qyweixin.corpid}")
    private String corpid;
    @Value("${qyweixin.secret}")
    private String secret;
    @Value("${qyweixin.agentid}")
    private String agentid;
    @Value("${qyweixin.serverUserid}")
    private String serverUserid;

    @Resource
    private TimeTasksService timeTaskService;
    @Resource
    private RedisService redisService;

    /**
     * 每天11点30检查10天内即将到期的服务
     */
    @Scheduled(cron = "0 30 11 * * ?")
    public void searchTask() {
        try {
            System.out.println("每天11点30检查10天内即将到期的服务");
            List<TimeTasks> tasks = timeTaskService.getExpireTask(10);
            if (CollectionUtils.isNotEmpty(tasks)) {
                StringBuilder content = new StringBuilder();
                LinkedHashMap<String, List<TimeTasks>> map = tasks.stream().collect(Collectors.groupingBy(TimeTasks::getCorpName,
                        LinkedHashMap::new, Collectors.toList()));
                for (Map.Entry<String, List<TimeTasks>> entry : map.entrySet()) {
                    String key = entry.getKey();
                    List<TimeTasks> value = entry.getValue();

                    content.append(key).append("[");
                    if (CollectionUtils.isNotEmpty(value)) {
                        LinkedHashMap<String, List<TimeTasks>> typeMap = value.stream().collect(Collectors.groupingBy(TimeTasks::getTypeName,
                                LinkedHashMap::new, Collectors.toList()));
                        for (Map.Entry<String, List<TimeTasks>> typeEntry : typeMap.entrySet()) {
                            String typeKey = typeEntry.getKey();
                            List<TimeTasks> typeValue = typeEntry.getValue();
                            content.append(typeKey).append(":");
                            for (int i = 0; i < typeValue.size(); i++) {
                                TimeTasks task = typeValue.get(i);
                                if (i != typeValue.size() - 1) {
                                    content.append(task.getIntro()).append("(")
                                            .append(DateUtil.getDefaultTime2DateStr(task.getExpireTime())).append(")").append(",");
                                } else {
                                    content.append(task.getIntro()).append("(")
                                            .append(DateUtil.getDefaultTime2DateStr(task.getExpireTime())).append(")").append(";");
                                }
                            }
                        }
                    }
                    content.append("]");
                }


                String accessToken = getQyAccessToken();
                QyWeiXinUtil.sendToUser(accessToken, agentid, serverUserid, QyWeixinMsg.checkAliyunServer(content.toString()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 每天7:00至22:00之间，每隔5分钟执行一次
     */
    @Scheduled(cron = "0 0/5 7-21 * * ?")
    public void checkXyxServer() throws Exception {
        if (AccountUtil.judgeProd(envi)) {
            String st = HttpUtils.get("https://lucky.xiaoyuxiang.com:8000/mechanism/system/test/checkServer");

            if (StringUtils.isBlank(st) || !st.contains("0")) {
                String accessToken = getQyAccessToken();
                QyWeiXinUtil.sendToUser(accessToken, agentid, serverUserid, QyWeixinMsg.checkXyxServer());
            }
        }
    }

    /**
     * 获取企业微信AccessToken
     */
    private String getQyAccessToken() {
        // 企业微信获取access_token
        String accessToken = (String) redisService.get(RedisParam.QYWEINXIN_ACCESS_TOKEN);
        if (StringUtils.isBlank(accessToken)) {
            AccessTokenDto dto = QyWeiXinUtil.getAccessToken(corpid, secret);
            if (dto != null) {
                accessToken = dto.getAccess_token();
                int expires_in = dto.getExpires_in();
                // redis缓存accessToken
                redisService.set(RedisParam.QYWEINXIN_ACCESS_TOKEN, accessToken, expires_in);
            }
        }
        return accessToken;
    }

}
